<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import qs from 'qs'
import { DeleteSubjectProduct, GetSubjectProductList, PatcSubjectProductType, PatchSubjectProductSort, PostCreateSubjectProduct } from '@/api/modules/subject'
import { GetAllData } from '@/api/modules/merchandiseControl'
import PageNumber from '@/store/modules/PageNumberCache'

const imgDomain = 'https://img1.eprhan.cc'
const route = useRoute()
const router = useRouter()
const PageNumberCache = PageNumber()

const dataList: any = reactive({
  list: [],
  productOption: [],
})

const loading = ref(true)
const total = ref(0)
let PageSize = 20

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    SubjectId: route.query.id,
  }
  await GetSubjectProductList(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
    else {
      ElMessage.error(`查询失败。${dataRes.errors}`)
      loading.value = false
    }
  })
    .catch(() => {
      loading.value = false
    })
  loading.value = false
}

// 修改状态
function ModifyType(params: any) {
  PatcSubjectProductType(params).then((res: any) => {
    if (res.statusCode === 200) {
      ElMessage.success('修改成功')
      // GetDataList(PageNum, PageSize)
    }
    else {
      ElMessage.error(`修改失败。${res.errors}`)
    }
  })
}

// 修改排序
function SortModification(message: any) {
  const params = {
    id: message.row.id,
    sort: message.row.sort,
  }
  PatchSubjectProductSort(params).then((res: any) => {
    if (res.data) {
      ElMessage.success('修改成功。')
    }
    else {
      ElMessage.error(`修改失败。${res.errors}`)
      GetDataList()
    }
  })
}

// 关联商品
interface ProductData {
  subjectId: any
  productId: any
  sort: number
  enable: boolean
  desp: string
}
const productData = ref<ProductData>({
  subjectId: route.query.id,
  productId: '',
  sort: 0,
  enable: true,
  desp: '',
})
const dialogVisible = ref(false)
function CorrelationProduct() {
  productData.value = {
    subjectId: route.query.id,
    productId: '',
    sort: 0,
    enable: true,
    desp: '',
  }
  dialogVisible.value = true
}

function SetProductData() {
  if (productData.value.productId === '') {
    ElMessage.error('请选择商品')
    return
  }
  // console.log(productData.value)
  const params = { ...productData.value }
  PostCreateSubjectProduct(params).then((res: any) => {
    if (res.statusCode === 200) {
      ElMessage.success('关联成功')
      dialogVisible.value = false
      GetDataList()
    }
    else {
      ElMessage.error(`关联失败。${res.errors}`)
    }
  })
}

// 删除
function Delete(id: number) {
  ElMessageBox.confirm(
    '您确定要删除该关联商品吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      DeleteSubjectProduct(id).then((res: any) => {
        if (res.statusCode === 200) {
          ElMessage.success('删除成功')
          GetDataList()
        }
        else {
          ElMessage.error(`删除失败。${res.errors}`)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 返回
function GetBack() {
  router.push({
    name: 'subjectIndex',
  })
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
  PageNumberCache.SetSubjectProjectPage(val)
}

const nowPageNum = computed(() => {
  return PageNumberCache.GetSubjectProjectPage()
})

onMounted(async () => {
  GetDataList(PageNumberCache.GetSubjectProjectPage())
  const params = qs.stringify({ ProductName: '', IsActive: true })

  await GetAllData(params).then((res: any) => {
    dataList.productOption = res.data
  })
})
</script>

<template>
  <div>
    <PageMain>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="CorrelationProduct">
          关联商品
        </el-button>
        <el-button @click="GetBack">
          返回
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="ID" width="100" />
        <el-table-column align="center" prop="subjectId" label="专题ID" width="100" />
        <el-table-column header-align="center" prop="productId" label="商品ID" width="300" />
        <el-table-column header-align="center" prop="productInfo.productName" label="商品名称" width="300" />
        <el-table-column align="center" prop="productInfo.flag" label="商品类型" width="100">
          <template #default="scope">
            <el-tag type="primary">
              {{ scope.row.productInfo?.flag === 1 ? '正常商品' : scope.row.productInfo?.flag === 2 ? '积分商品' : '秒杀商品' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="productInfo.cdnProductPhotoPic" label="CDN商品封面" width="120">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="imgDomain + scope.row.productInfo?.cdnProductPhotoPic" />
          </template>
        </el-table-column>
        <el-table-column header-align="center" prop="desp" label="描述" width="400" />
        <el-table-column align="center" prop="addTime" label="添加时间" width="240" />
        <el-table-column align="center" prop="updateTime" label="更新时间" width="240" />
        <el-table-column align="center" prop="sort" label="排序" fixed="right" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.sort" style="width: 120px;">
              <template #append>
                <el-button type="primary" size="small" @click="SortModification(scope)">
                  修改
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态" fixed="right" width="120">
          <template #default="scope">
            <el-switch
              v-model="scope.row.enable"
              @click="ModifyType({ id: scope.row.id, enable: scope.row.enable })"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" min-width="150">
          <template #default="scope">
            <el-button type="danger" @click="Delete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
    <el-dialog
      v-model="dialogVisible"
      title="关联商品"
      width="500"
    >
      <ElRow :gutter="20">
        <ElCol :md="24">
          <ElFormItem label="绑定商品">
            <el-select v-model="productData.productId" placeholder="请选择要绑定的商品">
              <el-option
                v-for="item in dataList.productOption"
                :key="item.productId" :label="item.productName" :value="item.productId"
              />
            </el-select>
          </ElFormItem>
        </ElCol>
        <ElCol :md="12">
          <ElFormItem label="是否可用">
            <el-switch
              v-model="productData.enable"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :md="12">
          <ElFormItem label="排序">
            <el-input v-model="productData.sort" type="number" placeholder="请输入排序" />
          </ElFormItem>
        </ElCol>
        <ElCol :md="24">
          <ElFormItem label="描述">
            <el-input v-model="productData.desp" type="textarea" placeholder="请输入描述" />
          </ElFormItem>
        </ElCol>
      </ElRow>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="SetProductData">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.scrollbar-flex-content {
  display: flex;
  max-width: 300px;

  .scrollbar-flex-img {
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: auto;
    height: 60px;
    margin-right: 10px;
  }
}
</style>
